import food from "./food";

export default class foodManager extends Laya.Script {
    // 更多参数说明请访问: https://ldc2.layabox.com/doc/?nav=zh-as-2-4-0
    FoodPrefabArr=[]
    spawnfoofArr=[]
    isPlay=false;
    columnArr=[];
    constructor() { super(); }
    
    onAwake(){
        
        Laya.SoundManager.playMusic("res/sound/bgm.wav",0);
        Laya.stage.on("gamerover",this,this.gamerOver)
        Laya.stage.on("gamerover3",this,this.gamerOver)
         Laya.stage.on("start",this,function(){this.isPlay=true;
                })
        this.loadFoodPrefab();
        
    }
    gamerOver(){
        this.isPlay=false
        this.spawnfoofArr.forEach(element => {
            element.removeSelf();
        });
    }
    onUpdate(){
       
    }
    loadFoodPrefab(){
        
        
        var pathArr=[
            "prefab/food_1.json",
            "prefab/food_2.json",
            "prefab/food_3.json",
            "prefab/shi_1.json",
        ]
        var infoArr=[];
        for(var i=0;i<pathArr.length;i++){
            infoArr.push({url:pathArr[i],type:Laya.Loader.PREFAB})
        }
        Laya.loader.load(infoArr,Laya.Handler.create(this,function(result){
            for(var i=0;i<pathArr.length;i++){
                this.FoodPrefabArr.push(Laya.loader.getRes(pathArr[i]))
            }
            this.ranTime=this.getRandom(300,800);
            Laya.timer.loop(this.ranTime,this,function(){
                this.spawn();
            })
        }))
    }
    spawn(){
        if(!this.isPlay)return;
        var arrY=[100,320,720]
        var x=2068;
        var y=arrY[this.getRandom(0,arrY.length-1)];
        var foodIndex=this.getRandom(0,this.FoodPrefabArr.length-1);
        var Food=Laya.Pool.getItemByCreateFun(foodIndex.toString(),function(){
            return this.FoodPrefabArr[foodIndex].create()},this);
            Laya.stage.getChildAt(0).getChildAt(0).addChild(Food);
            Food.pos(x,y);
            Food.getComponent(food).Init(foodIndex.toString());
            this.spawnfoofArr.push(Food);

    }
    getRandom(min,max){
        var value=Math.random()*(max-min);
        value=Math.round(value);
        return min+value;
        }
}